#include "Heap.h"

void Temp(HPDataType* a, HPDataType* b)
{
	HPDataType temp = *a;
	*a = *b;
	*b = temp;
}

void HeapInit(HP* php)
{
	assert(php);
	php->a = (HPDataType*)malloc(sizeof(HPDataType) * 4);
	if (php->a == NULL)
	{
		perror("HeapInit  malloc");
		return;
	}
	php->capacity = 4;
	php->size = 0;
}
//void HeapDestroy(HP* php);

void HeapPush(HP* php, HPDataType x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		HPDataType* temp = (HPDataType*)realloc(php->a,sizeof(HPDataType) * php->capacity * 2);
		
		if (temp == NULL)
		{
			perror("HeapPush relloc");
			return;
		}
		
		php->a = temp;
		temp = NULL;

		php->capacity *= 2;
	}
	
	php->a[php->size] = x;
	php->size++;

	AdjustUp(php->a, php->size - 1);
}

void HeapPop(HP* php)
{
	assert(php);
	assert(!HeapEmpty(php));

	Temp(&php->a[php->size - 1], &php->a[0]);
	php->size--;


	AdjustDown(php->a, php->size, 0);

	
}
HPDataType HeapTop(HP* php)
{
	assert(php);
	return php->a[0];
}


bool HeapEmpty(HP* php)
{
	return php->size == 0;
}

int HeapSize(HP* php)
{
	assert(php);
	return php->size;
}

void AdjustUp(HPDataType* a, int child)
{
	assert(a);
	int parent = 0;
	while (child > 0)
	{
		parent = (child - 1) / 2;
		if (a[child] > a[parent])
		{
			Temp(&a[child], &a[parent]);
			child = parent;
		}
		else
		{
			break;
		}
	}
}
void AdjustDown(HPDataType* a, int n, int parent)
{
	int child = parent * 2 + 1;
	
	while (child<n)
	{
		if (child + 1 < n && a[child] < a[child + 1])
		{
			child++;
		}
		
		if (a[parent] < a[child])
		{
			Temp(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}


}
